<template>
    <div class="app-container">
        <!-- 操作栏 -->
        <div class="mb-4 flex justify-between">
            <div>
                <el-button type="primary" @click="handleCreate">新建知识文档</el-button>
                <el-button @click="refreshList" style="margin-left: 10px">刷新列表</el-button>
            </div>
            <el-input v-model="searchKeyword" placeholder="搜索文档名称/内容" style="width: 300px" clearable
                @input="handleSearch" />
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredDocuments" border style="width: 100%" v-loading="loading">
            <el-table-column prop="docId" label="ID" width="80" />
            <el-table-column prop="docName" label="文档名称" width="200" />
            <el-table-column prop="docType" label="类型" width="120">
                <template #default="{ row }">
                    <el-tag :type="getDocTypeTag(row.docType)">{{docTypes.find(t => t.value === row.docType)?.label
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="version" label="版本" width="100">
                <template #default="{ row }">v{{ row.version }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="statusTagMap[row.status]">{{ statusMap[row.status] }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="relatedModels" label="关联模型" width="180">
                <template #default="{ row }">
                    <el-tag v-for="model in row.relatedModels" :key="model" type="info" style="margin-right: 5px">
                        {{ model }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="220" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    <el-button size="small" type="success" @click="handleViewVersions(row)">版本</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑文档' : '新建文档'" width="50%">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="文档名称" prop="docName">
                    <el-input v-model="form.docName" />
                </el-form-item>
                <el-form-item label="文档类型" prop="docType">
                    <el-select v-model="form.docType" placeholder="请选择文档类型">
                        <el-option v-for="type in docTypes" :key="type.value" :label="type.label" :value="type.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="关联模型">
                    <el-select v-model="form.relatedModels" multiple filterable placeholder="选择关联模型"
                        style="width: 100%">
                        <el-option v-for="model in availableModels" :key="model" :label="model" :value="model" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文档内容" prop="content">
                    <el-input v-model="form.content" type="textarea" :rows="6" />
                </el-form-item>
                <el-form-item label="上传文件">
                    <el-upload class="upload-demo" action="#" :limit="1" :file-list="fileList"
                        :on-change="handleFileChange" :auto-upload="false">
                        <el-button type="primary">选择文件</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持格式：PDF/DOCX/TXT，大小不超过50MB
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 版本对话框 -->
        <el-dialog v-model="versionDialogVisible" title="版本历史" width="60%">
            <el-table :data="versionData" border>
                <el-table-column prop="version" label="版本" width="100">
                    <template #default="{ row }">v{{ row.version }}</template>
                </el-table-column>
                <el-table-column prop="updateTime" label="更新时间" width="180" />
                <el-table-column prop="operator" label="操作人" width="120" />
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button size="small" type="text" @click="handleVersionRollback(row)">回滚</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态映射
const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已归档',
    3: '待审核'
}

const statusTagMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
}

// 文档类型选项
const docTypes = [
    { value: 'faq', label: '常见问题' },
    { value: 'technical', label: '技术文档' },
    { value: 'manual', label: '操作手册' },
    { value: 'policy', label: '政策法规' }
]

// 示例初始数据
const initialData = [
    {
        docId: 1,
        docName: 'SQL纠错手册',
        docType: 'manual',
        content: '...',
        version: 1.2,
        status: 1,
        relatedModels: ['gpt-4o'],
        updateTime: '2025-03-18 14:30',
        file: null
    },
    {
        docId: 2,
        docName: '常见SQL问题',
        docType: 'faq',
        content: '...',
        version: 2.0,
        status: 3,
        relatedModels: ['deepseek-r1'],
        updateTime: '2025-03-17 09:15',
        file: null
    }
]

// 可用模型列表（示例）
const availableModels = ref(['gpt-4o', 'deepseek-r1', 'qwen-coder:14b'])

const searchKeyword = ref('')
const dialogVisible = ref(false)
const versionDialogVisible = ref(false)
const isEdit = ref(false)
const loading = ref(false)
const form = ref({})
const documents = ref([...initialData])
const fileList = ref([])
const versionData = ref([])
const formRef = ref(null)

// 验证规则
const rules = {
    docName: [{ required: true, message: '请输入文档名称', trigger: 'blur' }],
    docType: [{ required: true, message: '请选择文档类型', trigger: 'change' }],
    content: [{ required: true, message: '请输入文档内容', trigger: 'blur' }]
}

// 过滤后的数据
const filteredDocuments = computed(() => {
    return documents.value.filter(
        (item) =>
            item.docName.includes(searchKeyword.value) ||
            item.content.includes(searchKeyword.value) ||
            item.docType.includes(searchKeyword.value)
    )
})

// 获取文档类型标签样式
const getDocTypeTag = (type) => {
    const typeMap = {
        faq: 'success',
        technical: 'warning',
        manual: 'primary',
        policy: 'danger'
    }
    return typeMap[type] || ''
}

// 文件处理
const handleFileChange = (file) => {
    form.value.file = file.raw
}

// 版本管理
const handleViewVersions = (row) => {
    // 示例版本数据
    versionData.value = [
        {
            docId: row.docId,
            version: 1.0,
            updateTime: '2025-03-15 10:00',
            operator: '张三'
        },
        {
            docId: row.docId,
            version: 1.1,
            updateTime: '2025-03-16 14:00',
            operator: '李四'
        }
    ]
    versionDialogVisible.value = true
}

// CRUD操作
const handleCreate = () => {
    isEdit.value = false
    form.value = {
        docId: null,
        docName: '',
        docType: '',
        content: '',
        version: 1.0,
        status: 0,
        relatedModels: [],
        file: null
    }
    fileList.value = []
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEdit.value = true
    form.value = { ...row }
    fileList.value = row.file ? [row.file] : []
    dialogVisible.value = true
}

const submitForm = async () => {
    await formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 更新文档时创建新版本
                const index = documents.value.findIndex(item => item.docId === form.value.docId)
                const newVersion = parseFloat(form.value.version) + 0.1
                documents.value.splice(index, 1, {
                    ...form.value,
                    version: newVersion.toFixed(1),
                    updateTime: new Date().toISOString()
                })
            } else {
                documents.value.push({
                    ...form.value,
                    docId: Date.now(),
                    updateTime: new Date().toISOString()
                })
            }
            dialogVisible.value = false
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        }
    })
}

const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该文档？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        documents.value = documents.value.filter((item) => item.docId !== row.docId)
        ElMessage.success('删除成功')
    })
}

const refreshList = async () => {
    loading.value = true
    // 这里可以添加API请求
    setTimeout(() => {
        loading.value = false
        ElMessage.success('刷新成功')
    }, 1000)
}
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.mb-4 {
    margin-bottom: 1rem;
}

.upload-demo {
    width: 100%;
}
</style>